import React, { useState, useEffect } from "react";
import { Table, Button, Modal, Form, Input, Select, message } from "antd";
import axios from "axios";
import dayjs from "dayjs";

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [form] = Form.useForm();
  function mergeUsersData(data) {
    const userMap = {};
  
    // 遍历原始数据，按 username 合并
    data.forEach((item) => {
      const username = item.username;
      
      if (!userMap[username]) {
        // 初始化用户记录
        userMap[username] = {
          count: 1,
          typeCounts: { [item.fortune_type]: 1 },
          latestTime: item.created_at,
          dominantType: item.fortune_type
        };
      } else {
        // 更新统计信息
        const user = userMap[username];
        user.count++;
        
        // 更新命理类型统计
        user.typeCounts[item.fortune_type] = (user.typeCounts[item.fortune_type] || 0) + 1;
        
        // 更新最新时间
        if (item.created_at > user.latestTime) {
          user.latestTime = item.created_at;
        }
        
        // 更新主流命理类型
        if (user.typeCounts[item.fortune_type] > user.typeCounts[user.dominantType]) {
          user.dominantType = item.fortune_type;
        }
      }
    });
  
    // 转换为结果数组
    return Object.keys(userMap).map(username => ({
      username,
      count: userMap[username].count,
      fortune_type: userMap[username].dominantType,
      created_at: userMap[username].latestTime
    }));
  }
  
  // 示例数据
  // const inputData = [
  //   {id: 1, username: '张三', fortune_type: '八字测算', created_at: '2025-04-10T07:52:27.000Z'},
  //   {id: 2, username: '李四', fortune_type: '紫微命盘', created_at: '2025-04-15T01:30:00.000Z'},
  //   {id: 3, username: '王五', fortune_type: '八字测算', created_at: '2025-04-19T17:58:00.000Z'},
  //   {id: 4, username: '奥迪', fortune_type: '八字测算', created_at: '2025-04-20T13:00:27.000Z'},
  //   {id: 5, username: '奥迪', fortune_type: '八字测算', created_at: '2025-04-20T13:00:47.000Z'},
  //   {id: 6, username: '叶凡', fortune_type: '八字测算', created_at: '2025-04-21T00:38:48.000Z'},
  //   {id: 7, username: '叶凡', fortune_type: '八字测算', created_at: '2025-04-21T00:38:48.000Z'},
  //   {id: 8, username: '无双', fortune_type: '八字测算', created_at: '2025-04-21T03:25:24.000Z'},
  //   {id: 9, username: '无双', fortune_type: '八字测算', created_at: '2025-04-21T03:25:46.000Z'},
  //   {id: 10, username: '张三丰', fortune_type: '八字测算', created_at: '2025-04-24T03:03:59.000Z'}
  // ];
  
  // 执行合并
  // const mergedData = mergeUsersData(inputData);
  // console.log(mergedData,'33333');
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/userfortune/allfortunes");
      // setUsers(response.data.map((user) => ({ ...user, disabled: user.disabled || false })));
      let {data}=response.data
      console.log(data)
      let newdata=mergeUsersData(data)
      console.log(newdata)
      setUsers(newdata,'new')
    } catch (error) {
      console.error("Error fetching users:", error);
      message.error("获取用户列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleEdit = (record) => {
    setCurrentUser(record);
    form.setFieldsValue({
      username: record.username,
      gender: record.gender || "未知",
      birthYear: record.birth_year || "",
      birthMonth: record.birth_month || "",
      birthDay: record.birth_day || "",
      birthHour: record.birth_hour || "",
    });
    setEditModalVisible(true);
  };

  const handleDisable = async (record) => {
    try {
      await axios.put(`http://localhost:5000/api/users/${record.username}`, {
        disabled: !record.disabled,
      });
      setUsers(users.map((user) => (user.username === record.username ? { ...user, disabled: !user.disabled } : user)));
      message.success(`${record.disabled ? "启用" : "禁用"}用户成功`);
    } catch (error) {
      console.error("Error updating user:", error);
      message.error("操作失败");
    }
  };

  const handleSave = async (values) => {
    try {
      await axios.put(`http://localhost:5000/api/users/${currentUser.username}`, values);
      setUsers(users.map((user) => (user.username === currentUser.username ? { ...user, ...values } : user)));
      setEditModalVisible(false);
      message.success("用户信息更新成功");
    } catch (error) {
      console.error("Error updating user:", error);
      message.error("更新用户信息失败");
    }
  };

  const columns = [
    { title: "用户名", dataIndex: "username", key: "user" },
    { title: "测算次数", dataIndex: "count", key: "fortune_count" },
    { title: "测算偏好", dataIndex: "fortune_type", key: "fortune_types" },
    { title: "最近测算时间", dataIndex: "last_fortune_time", key: "last_fortune_time", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
    { title: "状态", dataIndex: "disabled", key: "disabled", render: (disabled) => (disabled ? "已禁用" : "正常") },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <>
          <Button onClick={() => handleEdit(record)} style={{ marginRight: 8 }}>编辑</Button>
          <Button onClick={() => handleDisable(record)} type={record.disabled ? "primary" : "danger"}>
            {record.disabled ? "启用" : "禁用"}
          </Button>
        </>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      <Table
        columns={columns}
        dataSource={users}
        rowKey="username"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
      <Modal
        title="编辑用户信息"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleSave} layout="vertical">
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: "请输入用户名" }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item name="gender" label="性别">
            <Select>
              <Select.Option value="male">男</Select.Option>
              <Select.Option value="female">女</Select.Option>
              <Select.Option value="未知">未知</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="birthYear" label="出生年份">
            <Input placeholder="例: 1990" />
          </Form.Item>
          <Form.Item name="birthMonth" label="出生月份">
            <Input placeholder="例: 7" />
          </Form.Item>
          <Form.Item name="birthDay" label="出生日期">
            <Input placeholder="例: 1" />
          </Form.Item>
          <Form.Item name="birthHour" label="出生时辰">
            <Input placeholder="例: 子时 (23:00-00:59)" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;